<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href="/">权限管理</a></el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>  
        </el-breadcrumb>

        <!-- 卡片视图 -->
        <el-card>
            <!-- 添加角色按钮区域 -->
            <el-row>
              <el-col>
                  <el-button type="primary" @click="addDialogVisible=true">添加角色</el-button>
              </el-col>
            </el-row>

            <!-- 角色列表区域 -->
            <el-table :data="rolelist" border stripe>
                <!-- 展开列 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['bdbottom',i1 ===0 ? 'bdtop' : '', 'vcenter']" v-for=" (item1, i1) in scope.row.children" :key="item1.id">
                            <!-- 渲染一级权限 -->
                            <el-col :span="5">
                                <el-tag closable @close="removeRightsById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级、三级权限 -->
                            <el-col :span="19">
                                <!-- 用for循环来渲染二级权限 -->
                                <el-row :class="[i2 ===0 ? '' : 'bdtop', 'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
                                  <el-col :span="6">
                                     <el-tag closable type="success" @close="removeRightsById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                                     <i class="el-icon-caret-right"></i>
                                  </el-col>
                                  <el-col :span="18">
                                      <el-tag closable type="warning" v-for="(item3) in item2.children" :key="item3.id" @close="removeRightsById(scope.row, item3.id)">{{item3.authName}}</el-tag>
                                  </el-col>
                                </el-row>
                            </el-col>
                        </el-row>    
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column label="#" type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName" ></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc" ></el-table-column>
                <el-table-column label="操作"  >
                    <template slot-scope="scope">
                         <el-button type="primary" icon="el-icon-edit" size="mini"  @click="showEditorDialog(scope.row.id)">修改</el-button>
                         <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRoles(scope.row.id)">删除</el-button>
                         <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 添加新角色的对话框 -->
        <el-dialog
            title="添加角色"
            :visible.sync="addDialogVisible"
            width="30%"
            @closed="addDialogClosed"
            >
            <!-- 内容主体区域 -->
            <el-form :model="addForm" :rules="addRoleRules" ref="addRoleRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部 按钮区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRoles">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改角色的对话框 -->
        <el-dialog
            title="修改用户"
            :visible.sync="editorDialogVisible"
            width="50%"
            @closed="editDialogClosed">
           <el-form :model="editorForm" :rules="editFormRules" ref="editFormRef" label-width="100px" >
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editorForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editorForm.roleDesc"></el-input>
                </el-form-item>
           </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editorDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUserInfo">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 分配权限的对话框 -->
        <el-dialog
            title="分配权限"
            :visible.sync="setRightDialogVisible"
            width="50%"
            @close="setRightDialogClosed">
            <!-- 树形组件 -->
            <el-tree 
                :data="rightslist" 
                :props="treeProps"  
                show-checkbox 
                node-key="id" 
                default-expand-all
                :default-checked-keys="defKeys"
                ref="treeRef"
            ></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
export default {
    data() {
        return{
            // 所有角色列表数据
            rolelist: [],
            // 角色的权限数据
            rightslist: [],
            // 树形组件中默认选中的节点ID值数组
            defKeys: [],
            // 当前即将分配权限的角色id
            roleId: '',
            // 控制添加角色对话框的显示和隐藏
            addDialogVisible: false,
            // 控制修改角色对话框的显示和隐藏
            editorDialogVisible: false,
            // 添加角色的表单数据
            addForm:{
                roleName: '',
                roleDesc: ''
            },
            // 添加角色表单的验证规则对象
            addRoleRules:{
                roleName:[
                    {required: true, message: '请输入角色名称', trigger: 'blur'},
                    {min: 3, max: 10, message: '角色名称的长度在3~10个字符之间', trigger: 'blur'}
                ],
                roleDesc:[
                    {required: true, message: '请输入角色描述', trigger: 'blur'},
                    {min: 3, max: 10, message: '角色描述的长度在3~10个字符之间', trigger: 'blur'}
                ],
            },
            // 修改角色的表单数据
            editorForm: {},
            // 修改角色的表单数据的验证规则对象
            editFormRules:{
                roleName:[
                     {required: true, message: '请输入角色名称', trigger: 'blur'},
                     {min: 2, max: 10, message: '角色名称的长度在2~10个字符之间', trigger: 'blur'}
                ],
                roleDesc:[
                    {required: true, message: '请输入角色描述', trigger: 'blur'},
                    {min: 2, max: 10, message: '角色描述的长度在2~10个字符之间', trigger: 'blur'}
                ]
            },
            // 控制分配权限的对话框是否显示
            setRightDialogVisible:false,
            // 树形控件的属性绑定对象
            treeProps:{
                children: 'children',
                label: 'authName'
            }
        }
    },
    created() {
        this.getRolesList()
    },
    methods: {
        // 获取所有角色的列表
        async getRolesList() {
            const {data: res} = await this.$http.get('roles')

            if(res.meta.status !== 200) {
                return this.$message.error('角色列表获取失败！')
            }

            this.rolelist = res.data
        },
        // 监听添加角色对话框的关闭事件
        addDialogClosed() {
            this.$refs.addRoleRef.resetFields()
        },
        // 监听修改角色信息对话框关闭事件
        editDialogClosed(){
            this.$refs.editFormRef.resetFields()
        },
        // 点击确定按钮，添加新角色
        addRoles() {
            this.$refs.addRoleRef.validate( async valid =>{

                if(!valid) return
                const {data: res} = await this.$http.post('roles',this.addForm)
                if(res.meta.status !== 201){
                    this.$message.error('角色添加失败！')
                }

                this.$message.success('角色添加成功！')
                // 隐藏添加用户的对话框
                this.addDialogVisible = false
                // 重置对话框
                this.getRolesList()
            })
        },
        // 点击修改按钮
        async showEditorDialog(id){
            // console.log(id)
            const {data: res} = await this.$http.get('roles/' + id)
            if(res.meta.status !== 200){
                return this.$message.error('获取用户信息失败！')
            }

            this.editorForm = res.data
            this.editorDialogVisible = true

            console.log(this.editorForm.roleId);
        },
        // 点击确认，修改角色信息并提交
        editUserInfo(){
            this.$refs.editFormRef.validate(async valid=>{
                // console.log(valid);
                if(!valid) return
                // 发起修改角色信息的数据请求
                const {data: res} = await this.$http.put('roles/' + this.editorForm.roleId,{
                    roleName: this.editorForm.roleName,
                    roleDesc: this.editorForm.roleDesc
                })

                if(res.meta.status !== 200){
                    return this.$message.error('角色信息更新失败！')
                }

                // 关闭对话框
                this.editorDialogVisible = false
                // 刷新列表
                this.getRolesList()
                // 提示
                this.$message.success('角色信息更新成功！')
            })
        },
        // 根据roleId删除相应的角色
        async removeRoles(id) {
            // 弹框提示，是否确认删除
            const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(error =>{
                return error
            })

            // 如果用户确认删除，返回字符串为confirm
            // 如果用户取消，返回字符串为concle
            if(confirmResult !== 'confirm'){
                return this.$message.info('已取消删除操作')
            }

            const {data: res} = await this.$http.delete('roles/' + id)
            if(res.meta.status !== 200){
                return this.$message.error('删除失败!')
            }

            this.$message.success('删除成功')
            this.getRolesList() 
        },
        // 根据id删除对应的权限标签
        async removeRightsById(role,rightId){
            const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch( err => err)

            if(confirmResult !== 'confirm'){
                return this.$message.info('已取消删除操作')
            }

            const {data: res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
            if(res.meta.status !== 200){
                return this.$message.error('删除权限失败！')
            }
            
            // this.getRolesList()
            role.children = res.data
        },
        // 展示分配权限的对话框
        async showSetRightDialog(role){
            this.roleId = role.id
            // 获取当前角色现有的所有权限数据
            const {data: res} = await this.$http.get('rights/tree')
            if(res.meta.status !==200){
                return this.$message.error('权限获取失败！')
            }
            // 获取的权限数据保存到data中
            this.rightslist = res.data 
            // console.log(this.rightslist);

            // 调用getleafKeys函数，获取默认勾选上的三级权限
            this.getleafKeys(role, this.defKeys)

            this.setRightDialogVisible = true
        },
        // 通过递归的形式，获取一个角色下所有的三级权限id，保存到defKeys
        getleafKeys(node, arr){
            // 如果当前node节点不包含children属性，说明它就是三级节点
            if(!node.children){
                return arr.push(node.id)
            }

            node.children.forEach(item => 
            this.getleafKeys(item, arr))
        },
        // 监听分配权限对话框关闭，重置存储需要默认勾选的defKeys数组
        setRightDialogClosed(){
            this.defKeys = []
        },
        // 分配权限对话框，点击确认按钮提交勾选的权限
        async allotRights(){
            const key = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            const idStr = key.join(',')
            // console.log(key);
            const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids: idStr})
            if(res.meta.status !== 200){
                return this.$message.error('权限分配失败！')
            }

            this.$message.success('权限分配成功！')
            this.getRolesList()
            this.setRightDialogVisible = false
        }
    }
}
</script>

<style lang="less" scoped>
.el-tag{
    margin: 7px;
} 
.bdtop{
    border-top: 1px solid #eee;
}
.bdbottom{
    border-bottom: 1px solid #eee;
}
.vcenter{
    display: flex;
    align-items: center;
}
</style>